const { Controller } = require('egg')

class PhotoController extends Controller {
  // 获得照片列表
  async getPhotoList() {
    const { ctx, app } = this

    ctx.validate({
      page: {
        type: 'int',
        required: true,
        desc: '页码'
      },
      size: {
        type: 'int',
        required: false,
        desc: '每页数量'
      },
      tag: {
        type: 'string',
        required: false,
        desc: '标签'
      }
    })

    const { page, size = 20, tag } = ctx.request.body
    const offset = (page - 1) * size
    const limit = size
    const whereReg = tag ? { tag, status: 1 } : { status: 1 }
    const result = await app.model.PhotoList.findAndCountAll({
      where: whereReg,
      offset,
      limit,
      order: [['id', 'DESC']],
    })
    ctx.apiSuccess(result)
  }
  // 增加照片
  async addPhoto() {
    const { ctx, app, service } = this
    ctx.validate({
      url: {
        type: 'string',
        required: true,
        desc: '照片地址'
      },
      tag: {
        type: 'string',
        required: true,
        desc: '标签'
      }
    })
    const { url, tag } = ctx.request.body
    const result = await app.model.PhotoList.create({ photo_url: url, tag })
    if (!result) {
      const key = url.split('.myqcloud.com/')[1] // 获取 URL 中的文件路径部分
      await service.upload.deleteFile(key)
      return ctx.apiFail('添加失败')
    }
    ctx.apiSuccess(result)
  }
}

module.exports = PhotoController
